#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Author    :breeze
# @Time      :2019/4/10
# @Email     :wangbaoshan@bbdservice.com
# @File      :IC21_OvduCardAndQuasiCnt
# @Software  :PyCharm


'''eof
name:贷款和(准)贷记卡逾期账户数占比
code:IC21_OvduCardAndQuasiCnt_2D
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime
import pandas as pd

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]




def intCheck(str):
    try:
        int(str)
        return True
    except:
        return False


def ovduCardAndQuasiCnt():
    data = IC_DSJ_2D.get('data')
    factor1 = []
    factor2 = []
    factor3 = []
    # 信贷交易信息概要 PCO[1.1]
    PCO = getTable(data, 'PCO', 1, 0)
    if PCO == [{}]:
        factor1.append(None)
        factor2.append(None)
    elif PCO == 0:
        factor1.append(0)
        factor2.append(0)
    else:
        # 信贷交易信息概要信息单元 PC02[0.1]
        PC02 = getTable(PCO[0], 'PC02', 0, 0)
        if PC02 == [{}]:
            factor1.append(None)
            factor2.append(None)
        elif PC02 == 0:
            factor1.append(0)
            factor2.append(0)
        else:
            # 信贷交易提示信息段 PC02A[0.1]
            PC02A = getTable(PC02[0], 'PC02A', 0, 1)
            if PC02A == [{}]:
                factor2.append(None)
            elif PC02A == 0:
                factor2.append(0)
            else:
                # 账号数合计
                PC02AS01 = PC02A[0].get("PC02AS01")
                if PC02AS01 not in null_type_list and intCheck(PC02AS01):
                    factor2.append(int(PC02AS01))
                else:
                    factor2.append(None)
            # 逾期（透支）汇总信息段 PC02D[0,1]
            PC02D = getTable(PC02[0], 'PC02D', 0, 1)
            if PC02D == [{}]:
                factor1.append(None)
            elif PC02D == 0:
                factor1.append(0)
            else:
                # 逾期（透支）汇总信息 PC02DH[1.6]
                PC02DH = getTable(PC02D[0], 'PC02DH', 1, 1)
                if PC02DH == [{}]:
                    factor1.append(None)
                elif PC02DH == 0:
                    factor1.append(0)
                else:
                    if len(PC02DH) > 0:
                        for i in PC02DH:
                            # 账户数
                            PC02DS02 = i.get("PC02DS02")
                            if PC02DS02 not in null_type_list and intCheck(PC02DS02):
                                factor1.append(int(PC02DS02))
                            else:
                                factor1.append(None)
                    else:
                        factor1.append(None)

    # 借贷账户信息 PDA[1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        factor3.append(None)
    elif PDA == 0:
        factor3.append(0)
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            factor3.append(None)
        elif PD01 == 0:
            factor3.append(0)
        else:
            for i in PD01:
                # 基本信息段 PD01A[1.1]
                PD01A = getTable(i, 'PD01A', 1, 1)
                # 最新表现信息段 PD01B[1.1]
                PD01B = getTable(i, 'PD01B', 1, 1)
                if PD01A == [{}] or PD01B == [{}]:
                    continue
                elif PD01A == 0 or PD01B == 0:
                    factor3.append(0)
                else:
                    # 账号类型
                    PD01AD01 = PD01A[0].get("PD01AD01")
                    # 账户状态
                    PD01BD01 = PD01B[0].get("PD01BD01")
                    if PD01AD01 not in null_type_list and PD01BD01 not in null_type_list:
                        if (PD01AD01 == "R2" or PD01AD01 == "R3") and PD01BD01 == "6":
                            factor3.append(1)
                        else:
                            factor3.append(0)
                    else:
                        continue

    factor1 = [x for x in factor1 if x is not None]
    factor2 = [x for x in factor2 if x is not None]
    factor3 = [x for x in factor3 if x is not None]
    if len(factor1) == 0 or (len(factor2) == 0 and len(factor3) == 0):
        return u'缺失值'
    else:
        factor1 = sum(factor1) if len(factor1) > 0 else 0
        factor2 = sum(factor2) if len(factor2) > 0 else 0
        factor3 = sum(factor3) if len(factor3) > 0 else 0
        if factor1 == 0  and (factor2 ==factor3):
            return 0
        else:
            try:
                return '%.4f' % (factor1 / float(factor2 - factor3))
            except:
                return u'缺失值'



if __name__ == '__main__':
    file_obj = open(r'../../data/IC/IC21_OvduCardAndQuasiCnt/IC.json', 'r')
    content = file_obj.read()
    IC_DSJ_2D = json.loads(content, strict=False)
    aa = ovduCardAndQuasiCnt()
    print aa

result = ovduCardAndQuasiCnt()
